package alogrithm;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @author lbw
 * @version 1.0
 * @date 2021/10/18 12:25
 */
public class TopKstrings {
    public String[][] topKstrings (String[] strings, int k) {
        // write code here

        Map<String, Long> map = Arrays.stream(strings)
                .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
        List<String> list = Arrays.stream(strings).distinct().sorted((o1, o2) ->
            map.get(o1).equals(map.get(o2)) ?  o1.compareTo(o2) : map.get(o1).compareTo(map.get(o2))
        ).limit(k).collect(Collectors.toList());

        String[][] res = new String[k][2];
        for (int i = 0; i < k; ++i) {
            res[i][0] = list.get(i);
            res[i][1] = String.valueOf(map.get(res[i][0]));
        }
        return res;
    }
}
